package com.linkhub.oms.component.mp.wrapper;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.enums.WrapperKeyword;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 自定义QW，重写构建逻辑
 * @Author: echo
 * @Date: 2021/11/7 20:51
 * @Version: 1.0
 */
public class QueryWrapperAdapter<T> extends QueryWrapper<T> {

    /**
     * 添加查询条件
     *
     * @param mergeSegments mp内部存储的sql片段
     */
    public void addCondition(MergeSegments mergeSegments) {
        addSegments(WrapperKeyword.APPLY, mergeSegments.getNormal());
        addSegments(SqlKeyword.GROUP_BY, mergeSegments.getGroupBy());
        addSegments(SqlKeyword.HAVING, mergeSegments.getHaving());
        addSegments(SqlKeyword.ORDER_BY, mergeSegments.getOrderBy());
    }

    private void addSegments(ISqlSegment keyword, List<ISqlSegment> sqlSegments) {
        if (CollectionUtils.isEmpty(sqlSegments)) {
            return;
        }

        Collection<ISqlSegment> appendSegments = CollUtil.addAll(Lists.newArrayList(keyword), sqlSegments);
        ISqlSegment[] iSqlSegments = appendSegments.toArray(new ISqlSegment[]{});
        super.expression.add(iSqlSegments);
    }

    /**
     * 构造方法
     *
     * @param paramNameValuePairs 查询参数, key为mp自定义属性，不是实际的列
     * @param selectColumn        需要查询的字段
     */
    public QueryWrapperAdapter(Map<String, Object> paramNameValuePairs, String... selectColumn) {
        super.paramNameValuePairs = paramNameValuePairs;
        super.select(selectColumn);

    }

    /**
     * 构造方法
     *
     * @param paramNameValuePairs paramNameValuePairs
     */
    public QueryWrapperAdapter(Map<String, Object> paramNameValuePairs) {
        super.paramNameValuePairs = paramNameValuePairs;

    }

    public QueryWrapperAdapter() {
        super();
    }

}
